"use client";
import { useEffect, useState } from "react";
import { Tree, Spin } from "antd";
import type { TreeProps } from "antd";
import { getMenuList, getMenuTree } from "@common/api/menu_action";

interface MenuSelectorProps {
  value?: number[];
  onChange?: (value: number[]) => void;
  disabled?: boolean;
}



export default function MenuSelector({ value = [], onChange, disabled = false }: MenuSelectorProps) {
  const [treeData, setTreeData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [checkedKeys, setCheckedKeys] = useState<number[]>(value);

  useEffect(() => {
    setCheckedKeys(value);
  }, [value]);

  useEffect(() => {
    loadMenuData();
  }, []);

  const loadMenuData = async () => {
    try {
      const response = await getMenuTree() as any;
      if (response.code === 200) {
        const result = response.data;
        if (result) {
          let tree = formatTreeData(result || [])
          setTreeData(tree);
        }
      }
    } catch (error) {
      console.error('获取菜单数据失败:', error);
    } finally {
      setLoading(false);
    }
  };
  
  const onCheck: TreeProps['onCheck'] = (checkedKeysValue) => {
    const keys = Array.isArray(checkedKeysValue) ? checkedKeysValue : checkedKeysValue.checked;
    const numericKeys = keys.map(key => Number(key));
    setCheckedKeys(numericKeys);
    onChange?.(numericKeys);
  };

  const formatTreeData = (data: any[]): any[] => {
    if(!data) return [];
    if(data.length === 0) return [];
    return data.map(item => ({
      key: item.menu_id,
      title: item.menu_name,
      children: item.children ? formatTreeData(item.children) : undefined,
    }));
  };

  if (loading) {
    return <Spin />;
  }

  return (
    <Tree
      checkable
      checkedKeys={checkedKeys}
      onCheck={onCheck}
      treeData={treeData}
      disabled={disabled}
      height={300}
      style={{ border: '1px solid #d9d9d9', borderRadius: '6px', padding: '8px' }}
    />
  );
} 